import {BadRequestException, PipeTransform} from '@nestjs/common';

export interface ParseArrayOptions {
    items: any,          //需要吧数组中每一项转为什么格式
    separator?: string
}

const BooleanMap = {
    'true': true,
    'false': true
}



export class ParseArrayPipe implements PipeTransform<string, any[]> {
    constructor(private options?: ParseArrayOptions) {
    }

    transform(value: string, metadata): any[] {
        if (!value) return [];
        const {items = String, separator = ','} = this.options ?? {};
        return value.split(separator).map((item, index) => {
            // String === String
            if (items === String) {
                return item;
            } else if (items === Number) {
                let val = parseFloat(item);
                if (isNaN(val)) {
                    throw new BadRequestException(`[${index}] item must be a number`);
                }
                return val;
            } else if (items === Boolean) {
                if (BooleanMap[item]) return BooleanMap[item.toLowerCase()];
                else new BadRequestException(`[${index}] item must be a boolean`);
            }
        });
    }
}
